package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.xn.app.muying.R;
import com.xn.app.muying.adpter.OrderDetailAdapter;
import com.xn.app.muying.adpter.OrderDetailVIPAdapter;
import com.xn.app.muying.bean.OrderDetailBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Request;

/**
 * 订单列表
 * Created by Administrator on 2016/12/1.
 */
public class MineOrderDetailActivity extends BaseActivity {

    private ListView lv;
    private AlertDialog dialog;
    //数据库
    private DBManager db = null;
    private OrderDetailAdapter orderDetailAdapter;
    ArrayList<OrderDetailBean> list = null;
    //返回键
    private ImageView img_back = null;
    private OrderDetailVIPAdapter orderDetailVIPAdapter;
    //无数据页面
    private LinearLayout no_data_linearlayout = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mineorderdetail);
        db = new DBManager(MineOrderDetailActivity.this);
        lv = (ListView) findViewById(R.id.order_listview);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        if (MineOrderActivity.sign.equals("vip")) {
            orderDetailVIPAdapter = new OrderDetailVIPAdapter(MineOrderDetailActivity.this);
            lv.setAdapter(orderDetailVIPAdapter);
            getListData(2);
        } else {
            orderDetailAdapter = new OrderDetailAdapter(MineOrderDetailActivity.this);
            lv.setAdapter(orderDetailAdapter);
            getListData(1);
        }

    }

    private void getListData(final int id) {
        dialog = new MyAlertDialog().ShowDialog(MineOrderDetailActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.OrderDetail(id)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 200 || code == 204) {
                        onJsonData(bodys);
                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 1:
                    lv.setVisibility(ListView.VISIBLE);
                    if (MineOrderActivity.sign.equals("vip")) {
                        orderDetailVIPAdapter.getData(list);
                    } else {
                        orderDetailAdapter.getData(list);
                    }
                    break;
                case 2:
                    lv.setVisibility(ListView.GONE);
                    no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };

    private void onJsonData(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            JSONArray items = jsonObject.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String orderNumber = object.optString("orderNumber");
                String hospitalName = object.optString("hospitalName");
                String serviceTypeDescription = object.optString("serviceTypeDescription");
                String serviceProductName = object.optString("serviceProductName");
                String totalServiceCount = object.optString("totalServiceCount");
                String orderPrice = object.optString("orderPrice");
                String payMethodDescription = object.optString("payMethodDescription");
                String creationTime = object.optString("creationTime");
                String hospitalLogo = object.optString("hospitalLogo");
                String receiveStatusId = object.optString("receiveStatusId");
                String receiveStatusDescription = object.optString("receiveStatusDescription");
                String paymentStatusDescription = object.optString("paymentStatusDescription");

                OrderDetailBean orderDetailBean = new OrderDetailBean();
                orderDetailBean.setOrderNumber(orderNumber);
                orderDetailBean.setHospitalName(hospitalName);
                orderDetailBean.setServiceTypeDescription(serviceTypeDescription);
                orderDetailBean.setServiceProductName(serviceProductName);
                orderDetailBean.setTotalServiceCount(totalServiceCount);
                orderDetailBean.setOrderPrice(orderPrice);
                orderDetailBean.setPayMethodDescription(payMethodDescription);
                orderDetailBean.setCreationTime(creationTime);
                orderDetailBean.setHospitalLogo(hospitalLogo);
                orderDetailBean.setPaymentStatusDescription(paymentStatusDescription);
                orderDetailBean.setReceiveStatusDescription(receiveStatusDescription);
                orderDetailBean.setReceiveStatusId(receiveStatusId);
                list.add(orderDetailBean);
            }
            if(list.size()>0){
                loginHandler.sendEmptyMessage(1);
            }else{
                loginHandler.sendEmptyMessage(2);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
